package com.junjie.blibli.config;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.HttpMessageConverter;

import java.util.ArrayList;

@Configuration
public class JsonHttpMessageConverterConfig {

    @Bean
    @Primary
    public HttpMessageConverters fastJsonHttpMessageConvertes(){
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastConfig = new FastJsonConfig();
        //设置时间格式
        fastConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        fastConfig.setSerializerFeatures(
                /**
                 * 如果输出的json数据中键对应的值为null或不存在，正常情况下是同时忽略键和值不序列化，
                 * 这样的话前端就看不到了键字段了，因此需要加上这个配置将null转化成字符串
                 */
                SerializerFeature.WriteNullStringAsEmpty,
                //同上，不忽略空集合
                SerializerFeature.WriteNullListAsEmpty,
                //同上，不忽略空map
                SerializerFeature.WriteMapNullValue,
                //自动对Map进行排序，便于前端展示数据
                SerializerFeature.MapSortField,
                //禁用循环引用
                SerializerFeature.DisableCircularReferenceDetect,
                //就是输出更好看，格式化输出
                SerializerFeature.PrettyFormat
        );
        fastConverter.setFastJsonConfig(fastConfig);
        return new HttpMessageConverters(fastConverter);
    }

    //循环引用演示
    public static void main(String[] args) {
        ArrayList<Object> list = new ArrayList<>();
        Object o = new Object();
        list.add(o);
        list.add(o);
        System.out.println(list.size());
        //没有关闭循环引用打印结果  [{},{"$ref":"$[0]"}]
        //这是因为fastjson发现第二个对象是用过的，所以直接把地址拿过来了
        //但是这个打印的结果并不是我们想要的，就算我们重复添加，我们也是希望展示空的效果
        System.out.println(JSONObject.toJSONString(list));
        //关闭了循环引用打印结果  [{},{}]
        System.out.println(JSONObject.toJSONString(list,SerializerFeature.DisableCircularReferenceDetect));
    }
}
